package com.uhaou.system.action;

/*
 * Powered By [rapid-framework]
 * Web Site: http://www.rapid-framework.org.cn
 * Google Code: http://code.google.com/p/rapid-framework/
 * Since 2008 - 2010
 */ 

import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpSession;

import org.apache.commons.lang.xwork.StringUtils; 

import cn.org.rapid_framework.page.Page;
import cn.org.rapid_framework.web.scope.Flash;

import com.uhaou.common.base.BaseStruts2Action;
import com.uhaou.common.util.EasyUIJsonUtil;
import com.uhaou.common.util.Json; 
import com.uhaou.system.model.*; 
import com.uhaou.system.service.*; 
import com.uhaou.system.vo.query.*; 

import com.opensymphony.xwork2.ModelDriven;
import com.opensymphony.xwork2.Preparable;

/**
 * @author   
 * @version 1.0
 * @since 1.0
 */

public class SysFunctionAction extends BaseStruts2Action implements Preparable,
		ModelDriven {
	// 默认多列排序,example: username desc,createTime asc
	protected static final String DEFAULT_SORT_COLUMNS = null;

	// forward paths
	protected static final String QUERY_JSP = "/system/sysFunction/query.jsp";
	protected static final String LIST_JSP = "/system/sysFunction/list.jsp";
	protected static final String CREATE_JSP = "/system/sysFunction/create.jsp";
	protected static final String EDIT_JSP = "/system/sysFunction/edit.jsp";
	protected static final String SHOW_JSP = "/system/sysFunction/show.jsp";
	private static final String LOGIN_JSP = "/admin/frame.jsp";
	private static final String SUCCESS_JSP = "/admin/frame.jsp";
	// redirect paths,startWith: !
	protected static final String LIST_ACTION = "!/system/sysFunction/list.jsp";

	private ISysFunctionManager sysFunctionManager;  
	private ISysUserManager sysUserManager;
	
	private SysFunction sysFunction;
	java.lang.String id = null;
	private String ids;

	

	public void setSysUserManager(ISysUserManager sysUserManager) {
		this.sysUserManager = sysUserManager;
	}

	// 获取登录的用户名
	public String userName;
	// 获取输入的密码
	public String password;

	public String getUserName() {
		return userName;
	}

	public void setUserName(String userName) {
		this.userName = userName;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public void setIds(String ids) {
		this.ids = ids;
	}

	public void setParam(String param) {
		this.param = param;
	}

	private String param;

	public void prepare() throws Exception {
		if (isNullOrEmptyString(id)) {
			sysFunction = new SysFunction();
		} else {
			sysFunction = (SysFunction) sysFunctionManager.getById(id);
		}
	}

	/** 增加setXXXX()方法,spring就可以通过autowire自动设置对象属性,注意大小写 */
	public void setSysFunctionManager(ISysFunctionManager manager) {
		this.sysFunctionManager = manager;
	}

	public Object getModel() {
		return sysFunction;
	}

	public void setFuncId(java.lang.String val) {
		this.id = val;
	}

	/** 执行搜索 */
	public String list() {
		if (StringUtils.isNotBlank(param)) {
			SysFunctionQuery query = newQuery(SysFunctionQuery.class,
					DEFAULT_SORT_COLUMNS);

			Page page = sysFunctionManager.findPage(query);
			savePage(page,query);
			Map map = new HashMap();
			map.put("total", page.getTotalCount());
			map.put("rows", page.getResult());
			return writeAjaxResponse(Json.toJson(map));
		} else
			return LIST_JSP;
	}

	/** 查看对象 */
	public String show() {

		return SHOW_JSP;
	}

	/**
	 * 登录时Ajax校验用户名和密码是否正确 
	 * mayunbo 
	 * 2010-10-20
	 */
	@SuppressWarnings("unchecked")
	public String checkUser() {
		// 初始化result
		int result = 0;
		// 初始化message
		String message = "";
		// 用户名和密码为空的时候
		if ((userName.equals("")) && (password.equals(""))) {
			result = 1;
			message = "请输入用户名和密码";
		}
		// 用户名为空的时候
		else if (userName.equals("")) {
			result = 2;
			message = "请输入用户名";
		}
		// 密码为空的时候
		else if (password.equals("")) {
			result = 3;
			message = "请输入密码";
		} else {
			SysUserQuery query = new SysUserQuery();
			// 设置一个很大的pagesize便于查询
			query.setPageSize(10000);
			// 设置查询delete状态为非删除的状态
			 
			// 执行查询操作
			Page<SysUser> page = sysUserManager.findPage(query);
			// 查询出用户list
			List<SysUser> userlist = page.getResult();
			// 循环用户list，判断用户名和密码的正确性
			for (SysUser u : userlist) {
				// 用户名和密码都正确的时候
				if ((u.getUserName().equals(userName))
						&& (u.getUserPwd().equals(password))) {
					result = 0;
					message = "success";
					break;
				}
				// 用户名正确，密码不正确的时候
				else if ((u.getUserName().equals(userName))
						&& !(u.getUserPwd().equals(password))) {
					result = 1;
					message = "请输入正确的密码";
					break;
				}
				// 输入的用户名不正确的时候
				else if (!(u.getUserName().equals(userName))) {
					result = 2;
					message = "请输入正确的用户名";
				}
			}
		}
		// 将显示状态和显示信息封装到map中
		Map map = new HashMap();
		map.put("result", result);
		map.put("message", message);
		// 转化为json的格式串到页面上
		return writeAjaxResponse(Json.toJson(map));
	}

	/**
	 * 
	 *jiangcheng 
	 */
	@SuppressWarnings("unchecked")
	public String login() {
		// 用户名不为空的时候，放到session中
		if (userName != null&&password!=null&&!userName.trim().equals("")&&!password.trim().equals("")) {
			SysUserQuery query = newQuery(SysUserQuery.class,
					DEFAULT_SORT_COLUMNS);
			query.setUserName(userName);
			query.setUserPwd(password);
			Page page=sysUserManager.findPage(query);
			List list=page.getResult();
			if(list!=null&&list.size()>0){
				 
				return SUCCESS_JSP;
			}
			
		}
		return LOGIN_JSP;
	}

	/** 进入新增页面 */
	public String create() {
		String parentId = getText("parentId");
		if (param != null) {
			SysFunctionQuery query = newQuery(SysFunctionQuery.class,
					DEFAULT_SORT_COLUMNS);
			// 设置一个很大的pagesize
			query.setPageSize(10000);
			Page page = sysFunctionManager.findPage(query);
			List<SysFunction> list = page.getResult();
			List<Map> treedataList = new ArrayList<Map>();
			for (SysFunction f : list) {
				Map<String, Object> map = new HashMap();
				map.put("id", f.getId());
				map.put("parentId", f.getParentId());
				map.put("order", f.getFuncCode());
				map.put("text", f.getFuncName());
				map.put("utl", f.getFuncUrl());
				map.put("iconCls", "icon-ok");
				// 把其他附加值放到attribute字段
				Map amap = new HashMap();
				amap.put("order", f.getFuncCode());
				amap.put("url", f.getFuncUrl());
				amap.put("valid", f.getFuncType());
				amap.put("memo", f.getMemo());
				amap.put("parentId", f.getParentId());
				map.put("attributes", amap);
				treedataList.add(map);
			}
			Map<String, Object> root = new HashMap();
			root.put("id", "-1");
			root.put("text", "功能点");
			root.put("iconCls", "icon-ok");

			try {
				String jsonStr = EasyUIJsonUtil.createTreeJsonString(root,
						treedataList);
				getResponse().getWriter().write(jsonStr);
				return null;
			} catch (IOException e) {
				e.printStackTrace();
				return null;
			}
		} else
			return CREATE_JSP;

	}

	/** 保存新增对象 */
	public String save() {
		try {
			sysFunctionManager.save(sysFunction);
			Flash.current().success(CREATED_SUCCESS); // 存放在Flash中的数据,在下一次http请求中仍然可以读取数据,error()用于显示错误消息

			return writeAjaxResponse("1");
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	/** 进入更新页面 */
	public String edit() {
		return EDIT_JSP;
	}

	/** 保存更新对象 */
	public String update() {
		sysFunctionManager.update(this.sysFunction);
		Flash.current().success(UPDATE_SUCCESS);
		try {
			getResponse().getWriter().write("1");
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
		// return LIST_ACTION;
	}

	/** 删除对象 */
	public String delete() {
		String[] idsArray = ids.split(",");
		for (String id : idsArray) {
			sysFunctionManager.removeById(id);
		}
		Flash.current().success(DELETE_SUCCESS);
		return LIST_ACTION;
	}
	
	/**
	 * 权限树
	 * jiangcheng 
	 */
	public String rightTreeAjax(){
		// 从session中获取到用户名和密码
		userName ="";
		// 通过用户名获取用户的操作权限
		
		//List<SysFunction> userFuncList = sysFunctionManager.getUserFunc(userName);
	    
		
		List<SysFunction> userFuncList = sysFunctionManager.getFuncnodeList("");
		
		String userId = "";
		 
		// 初始化显示tree的list
		List<Map> treedataList = new ArrayList<Map>();
		// 初始化去重的操作权限list
		 
		if ((userFuncList != null) && (userFuncList.size() > 0)) {
			 
			for (SysFunction t : userFuncList) {
				Map amap = new HashMap();
				// 权限url，便于左侧菜单点击
				amap.put("url", t.getFuncUrl());
				// 将树形显示需要的属性封装到map中
				Map<String, Object> map = new HashMap();
				map.put("id", t.getId());
				map.put("parentId", t.getParentId());
				map.put("order", 1);
				map.put("text", t.getFuncName());
				map.put("iconCls", "icon-menu");
				map.put("attributes", amap);
				// 将map放入list中在树上展示
				treedataList.add(map);
			}
		}
		// 设定树的顶级节点的属性值
		Map<String, Object> root = new HashMap();
		root.put("id", "-1");
		root.put("text", "Home");
		root.put("iconCls", "icon-menu"); 
		root.put("url", "#"); 
		Map amap = new HashMap();
		amap.put("deptCode", "");
		root.put("attributes", amap);
		String jsonStr = EasyUIJsonUtil.createTreeJsonString(root,
				treedataList);
		return writeAjaxResponse(jsonStr);
	}

}

